#!/bin/env python
# -*- coding: utf-8 -*-

"""
File Name: setup.py
Author: morre <morre@vip.qq.com>
Create Time: 2022/12/31 23:05:34
Brief:
"""

from __future__ import absolute_import
import os
import logging
import sys
import shutil
import subprocess
from setuptools import setup, find_packages
from distutils.command.build_py import build_py as _build_py
from distutils.command.clean import clean as _clean
from distutils.spawn import find_executable

# Find the Protocol Compiler.
if "PROTOC" in os.environ and os.path.exists(os.environ["PROTOC"]):
    protoc = os.environ["PROTOC"]
else:
    protoc = find_executable("protoc")


def get_requirements():
    """Gets the requirements from requirements.txt"""
    the_lib_folder = os.path.dirname(os.path.realpath(__file__))
    requirement_path = the_lib_folder + "/requirements.txt"
    install_requires = []
    if os.path.isfile(requirement_path):
        with open(requirement_path, encoding="utf8") as f:
            install_requires = f.read().splitlines()
    return install_requires


def get_version():
    """Gets the version from hbase_client/version.py"""

    with open(
            os.path.join("hbase_client", "version.py"),
            encoding="utf8") as version_file:
        exec(version_file.read(), globals())  # pylint: disable=exec-used
        # pylint: disable=undefined-variable
        return __version__  # type: ignore


def generate_proto(source):
    """Invokes the Protocol Compiler to generate a _pb2.py from the given
    .proto file.  Does nothing if the output already exists and is newer than
    the input."""

    output = source.replace(".proto", "_pb2.py")

    if (not os.path.exists(output)
        or (os.path.exists(source) and
            os.path.getmtime(source) > os.path.getmtime(output))):
        logging.info("Generating %s...", output)

        if not os.path.exists(source):
            logging.warning("Can't find required file: %s", source)
            sys.exit(-1)

        if protoc is None:
            logging.warning(
                "protoc is not installed.  Please compile it "
                "or install the binary package.")
            sys.exit(-1)

        protoc_command = [
            protoc, "-Ihbase_client/pb", "--python_out=hbase_client/pb",
            "--proto_path=hbase_client/pb", source]
        if subprocess.call(protoc_command) != 0:
            sys.exit(-1)
        if subprocess.call(
            ["sed -i -E 's/^import.*_pb2/from . \\0/'"
             " hbase_client/pb/*_pb2.py"],
                shell=True) != 0:
            sys.exit(-1)


class Cleaner(_clean):
    """清除构建中间文件"""

    def run(self):
        # Delete generated files in the code tree.
        for (dirpath, _, filenames) in os.walk("."):
            for filename in filenames:
                filepath = os.path.join(dirpath, filename)
                for suffix in ["_pb2.py", ".bak", ".pyc", ".so", ".o"]:
                    if filepath.endswith("__init__.py"):
                        continue
                    if filepath.endswith(suffix):
                        os.remove(filepath)
        # _clean is an old-style class, so super() doesn't work.
        _clean.run(self)

        # remove build/dist dirs
        for dirname in [
            "build", "dist", "hbase_client.egg-info",
                "hbase_client/__pycache__", "hbase_client/pb/__pycache__"]:
            try:
                logging.info("Remove directory %s", dirname)
                shutil.rmtree(dirname)
            except FileNotFoundError as _:
                # ignore not exist directory.
                logging.warning("Remove ignore not exist directory %s", dirname)
                continue


class Builder(_build_py):
    """代码构建类"""

    def run(self):
        # Generate necessary .proto file if it doesn"t exist.

        for (dirpath, _, filenames) in os.walk("hbase_client/pb"):
            for filename in filenames:
                filepath = os.path.join(dirpath, filename)
                generate_proto(filepath)
        # _build_py is an old-style class, so super() doesn't work.
        _build_py.run(self)


logging.basicConfig(
    level=logging.DEBUG,
    format="%(asctime)s  %(filename)s[line:%(lineno)d] %(levelname)s "
    "%(message)s",
    datefmt="%a, %d %b %Y %H:%M:%S")


setup(
    name="hbase-client",
    version=get_version(),
    description="Pure Python Native HBase Client",
    url="https://gitee.com/morre/hbase_client",
    author="morre, sjzlyl406",
    author_email="morre@vip.qq.com, sjzlyl406@163.com",
    license="",
    classifiers=[
        "Development Status :: 4 - Beta",
        "Intended Audience :: Developers",
        "Topic :: Software Development :: Build Tools",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.9",
    ],
    keywords="python hbase client",
    packages=find_packages(),
    cmdclass={
        "clean": Cleaner,
        "build_py": Builder,
    },
    install_requires=[
        "setuptools>=65.6.3",
        "intervaltree>=3.0.2",
        "kazoo>=1.12.0",
        "protobuf>=3.9.2",
        "gevent>=1.4.0",
    ],
)


# python setup.py sdist  # 打包到dist目录中
